#!/bin/bash

# IdeaForge Setup Script
# This script sets up the development environment for IdeaForge

set -e

echo "🚀 Setting up IdeaForge development environment..."

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "❌ Node.js is not installed. Please install Node.js 18+ first."
    exit 1
fi

# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
if [ "$NODE_VERSION" -lt 18 ]; then
    echo "❌ Node.js version 18+ is required. Current version: $(node -v)"
    exit 1
fi

echo "✅ Node.js version: $(node -v)"

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "❌ npm is not installed. Please install npm first."
    exit 1
fi

echo "✅ npm version: $(npm -v)"

# Install dependencies
echo "📦 Installing dependencies..."
npm install

# Create environment file if it doesn't exist
if [ ! -f .env.local ]; then
    echo "🔧 Creating .env.local file..."
    cp env.example .env.local
    echo "✅ Created .env.local - Please update it with your configuration"
else
    echo "✅ .env.local already exists"
fi

# Create necessary directories
echo "📁 Creating necessary directories..."
mkdir -p apps/web/src/components
mkdir -p apps/web/src/lib
mkdir -p apps/web/src/types
mkdir -p apps/web/src/utils
mkdir -p apps/web/public

# Create basic component files
echo "🔧 Creating basic component files..."

# Create Button component
cat > apps/web/src/components/Button.tsx << 'EOF'
import { forwardRef } from 'react';
import { cn } from '@/utils/cn';

interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'outline' | 'ghost' | 'destructive';
  size?: 'sm' | 'md' | 'lg';
}

export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant = 'primary', size = 'md', ...props }, ref) => {
    return (
      <button
        className={cn(
          'btn',
          `btn-${variant}`,
          `btn-${size}`,
          className
        )}
        ref={ref}
        {...props}
      />
    );
  }
);

Button.displayName = 'Button';
EOF

# Create Input component
cat > apps/web/src/components/Input.tsx << 'EOF'
import { forwardRef } from 'react';
import { cn } from '@/utils/cn';

interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}

export const Input = forwardRef<HTMLInputElement, InputProps>(
  ({ className, ...props }, ref) => {
    return (
      <input
        className={cn('input', className)}
        ref={ref}
        {...props}
      />
    );
  }
);

Input.displayName = 'Input';
EOF

# Create utility files
echo "🔧 Creating utility files..."

cat > apps/web/src/utils/cn.ts << 'EOF'
import { clsx, type ClassValue } from 'clsx';

export function cn(...inputs: ClassValue[]) {
  return clsx(inputs);
}
EOF

# Create types file
cat > apps/web/src/types/index.ts << 'EOF'
export interface User {
  id: string;
  email: string;
  name?: string;
  image?: string;
  locale: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface Project {
  id: string;
  name: string;
  description?: string;
  ownerUserId: string;
  locale: string;
  status: 'active' | 'archived';
  createdAt: Date;
  updatedAt: Date;
}

export interface Intake {
  id: string;
  projectId: string;
  problem: string;
  valueProposition: string;
  targetUsers: any[];
  assumptions: any[];
  marketHints: any[];
  competitionHints: any[];
  createdAt: Date;
  updatedAt: Date;
}
EOF

# Create lib files
echo "🔧 Creating library files..."

cat > apps/web/src/lib/auth.ts << 'EOF'
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';

export async function getSession() {
  return await getServerSession(authOptions);
}

export async function getCurrentUser() {
  const session = await getSession();
  return session?.user;
}
EOF

cat > apps/web/src/lib/db.ts << 'EOF'
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import { env } from '@idea-forge/config';

const client = postgres(env.DATABASE_URL);
export const db = drizzle(client);
EOF

# Create API route files
echo "🔧 Creating API route files..."

mkdir -p apps/web/src/app/api/auth/\[...nextauth\]
cat > apps/web/src/app/api/auth/\[...nextauth\]/route.ts << 'EOF'
import NextAuth from 'next-auth';
import { authOptions } from './auth';

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
EOF

cat > apps/web/src/app/api/auth/\[...nextauth\]/auth.ts << 'EOF'
import { NextAuthOptions } from 'next-auth';
import { env } from '@idea-forge/config';

export const authOptions: NextAuthOptions = {
  providers: [],
  session: {
    strategy: 'jwt',
  },
  secret: env.NEXTAUTH_SECRET,
  pages: {
    signIn: '/auth/signin',
  },
  callbacks: {
    async session({ session, token }) {
      if (token) {
        session.user.id = token.sub!;
      }
      return session;
    },
    async jwt({ token, user }) {
      if (user) {
        token.id = user.id;
      }
      return token;
    },
  },
};
EOF

# Create health check API
mkdir -p apps/web/src/app/api/health
cat > apps/web/src/app/api/health/route.ts << 'EOF'
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ status: 'ok', timestamp: new Date().toISOString() });
}
EOF

# Create database health check
cat > apps/web/src/app/api/health/db/route.ts << 'EOF'
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET() {
  try {
    // Simple query to test database connection
    await db.execute(sql`SELECT 1`);
    return NextResponse.json({ status: 'ok', database: 'connected' });
  } catch (error) {
    return NextResponse.json(
      { status: 'error', database: 'disconnected', error: error.message },
      { status: 500 }
    );
  }
}
EOF

# Create ESLint config
cat > apps/web/.eslintrc.json << 'EOF'
{
  "extends": ["next/core-web-vitals"],
  "rules": {
    "@typescript-eslint/no-unused-vars": "error",
    "@typescript-eslint/explicit-function-return-type": "warn"
  }
}
EOF

# Create Prettier config
cat > .prettierrc << 'EOF'
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}
EOF

# Create .gitignore
cat > .gitignore << 'EOF'
# Dependencies
node_modules/
.pnp
.pnp.js

# Testing
coverage/

# Next.js
.next/
out/
build/
dist/

# Production
build/

# Misc
.DS_Store
*.pem

# Debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Local env files
.env*.local
.env

# Vercel
.vercel

# TypeScript
*.tsbuildinfo
next-env.d.ts

# Turbo
.turbo

# IDE
.vscode/
.idea/
*.swp
*.swo

# OS
Thumbs.db
EOF

echo "✅ Setup completed successfully!"
echo ""
echo "🎉 Next steps:"
echo "1. Update .env.local with your configuration"
echo "2. Run 'npm run dev' to start the development server"
echo "3. Open http://localhost:3000 in your browser"
echo ""
echo "📚 Documentation:"
echo "- README.md - Project overview and setup"
echo "- design-repo/ - Design documents and specifications"
echo ""
echo "🚀 Happy coding!" 